<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\command\analysis\material;

use app\command\BaseWork;
use app\enum\ConfigEnum;
use app\enum\OceanEnum;
use app\model\OeProjectPromotionModel;
use app\service\analysis\data\info\OceanUseMaterialService;
use think\console\Input;
use think\console\Output;
use think\facade\Cache;

class OceanUseWork extends BaseWork
{
    protected function configure()
    {
        // 指令配置
        $this->setName('analysis_ocean_use_work');
        // 设置参数
        $this->setDescription('数据分析-巨量素材使用打标');
    }

    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);

        $redis = Cache::store('redis')->handler();
        $obj = new OceanUseMaterialService();
        $t = time();
        $runTime = 5 * 60;

        $redisKey = ConfigEnum::CACHE_CONFIG[OceanEnum::BATCH_CONFIG_KEY]['mongo_oe_material_use'];
        while (time() - $t <= $runTime) {
            $id = $redis->lpop($redisKey);
            if (! $id) {
                $this->getOutputMessage('暂无数据');
                sleep(rand(5, 10));
                continue;
            }
            $model = (new OeProjectPromotionModel())->where(['id' => $id])->findOrEmpty();
            try {
                $this->getOutputMessage('刷新[' . $id . ']开始');
                if (! $obj->runTask($model)) {
                    $this->getOutputMessage('刷新[' . $id . ']失败:' . $obj::getError(0));
                }
                $this->getOutputMessage('刷新[' . $id . ']完成');
            } catch (\Exception $e) {
                $this->getOutputMessage('错误：' . $e->getMessage());
                echo $e->getLine() . PHP_EOL;
                echo $e->getFile() . PHP_EOL;
                echo $e->getTraceAsString() . PHP_EOL;
            }
        }
        $this->getOutputMessage('素材使用刷新结束');
    }
}
